import React, { useState, useRef } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, Upload, message } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import RichTextEditor from '@/components/RichTextEditor';
import { 
  qryIndustryNewsListPage,
  qryIndustryNewsDetail,
  addIndustryNews,
  updateIndustryNews,
  deleteIndustryNews
} from '@/services/news';
import { uploadMinio } from '@/services/common';

interface NewsItem {
  newsId: string;
  newsTitle: string;
  picUrl: string;
  newsItemContentBind?: string;
}

const NewsPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentNews, setCurrentNews] = useState<NewsItem | null>(null);
  const [imageUrl, setImageUrl] = useState('');
  const [editorContent, setEditorContent] = useState('');
  const [confirmLoading, setConfirmLoading] = useState(false);

  const columns: ProColumns<NewsItem>[] = [
    {
      title: '资讯编号',
      dataIndex: 'newsId',
      key: 'newsId',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '资讯标题',
      dataIndex: 'newsTitle',
      key: 'newsTitle',
    },
    {
      title: '资讯配图',
      dataIndex: 'picUrl',
      hideInSearch: true,
      key: 'picUrl',
      width: 150,
      render: (text: any) => (
        text ? (
          <img
            src={text}
            alt="资讯配图"
            style={{ width: '80px', height: '45px', objectFit: 'cover' }}
          />
        ) : '无图片'
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          onClick={() => handleEdit(record.newsId)}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          danger
          onClick={() => handleDelete(record.newsId)}
        >
          删除
        </Button>,
      ],
    },
  ];

  const handleAdd = () => {
    form.resetFields();
    setEditorContent('');
    setImageUrl('');
    setCurrentNews(null);
    setModalVisible(true);
  };

  const handleEdit = async (newsId: string) => {
    try {
      const detail = await qryIndustryNewsDetail({ newsId });
      setCurrentNews(detail);
      setImageUrl(detail.picUrl || '');
      setEditorContent(detail.newsItemContentBind || '');
      form.setFieldsValue(detail);
      setModalVisible(true);
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  const handleDelete = async (newsId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条资讯吗？',
      onOk: async () => {
        await deleteIndustryNews({ newsId });
        message.success('删除成功');
        actionRef.current?.reload();
      }
    });
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);
      
      const submitData = {
        ...values,
        picUrl: imageUrl,
        newsItemContentBind: editorContent
      };

      if (currentNews) {
        await updateIndustryNews({
          ...submitData,
          newsId: currentNews.newsId
        });
        message.success('更新成功');
      } else {
        await addIndustryNews(submitData);
        message.success('新增成功');
      }

      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setConfirmLoading(false);
    }
  };

  const uploadProps: any = {
    beforeUpload: (file: File) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) message.error('只能上传图片文件!');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) message.error('图片大小不能超过2MB!');
      return isImage && isLt2M;
    },
    // @ts-ignore
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        const response = await uploadMinio(file as File);
        if (response.data?.fileUrl) {
          setImageUrl(response.data.fileUrl);
          form.setFieldsValue({ picUrl: response.data.fileUrl });
          onSuccess?.(response, new XMLHttpRequest());
        } else {
          onError?.(new Error('上传失败'), new XMLHttpRequest());
        }
      } catch (error) {
        onError?.(error as Error, new XMLHttpRequest());
      }
    }
  };

  return (
    <PageContainer>
      <ProTable<NewsItem>
        actionRef={actionRef}
        rowKey="newsId"
        columns={columns}
        request={async (params) => {
          const { current, pageSize, newsTitle } = params;
          const result = await qryIndustryNewsListPage({
            pageIndex: current,
            pageSize,
            param: {
              newsTitle
            }
          });
          return {
            data: result.list,
            total: result.total,
            success: true,
          };
        }}
        toolBarRender={() => [
          <Button 
            key="add" 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增资讯
          </Button>,
        ]}
      />

      <Modal
        title={currentNews ? '编辑资讯' : '新增资讯'}
        open={modalVisible}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          {currentNews && (
            <Form.Item name="newsId" label="资讯编号" hidden>
              <Input disabled />
            </Form.Item>
          )}
          <Form.Item
            name="newsTitle"
            label="资讯标题"
            rules={[{ required: true, message: '请输入资讯标题' }]}
          >
            <Input placeholder="请输入资讯标题" maxLength={100} />
          </Form.Item>

          <Form.Item
            name="picUrl"
            label="资讯图片URL"
            rules={[{ required: true, message: '请上传图片' }]}
          >
            <Input
              placeholder="图片URL将在上传后自动填入"
              disabled
              style={{ color: 'rgba(0, 0, 0, 0.65)' }}
            />
          </Form.Item>

          <Form.Item label="上传图片">
            <Upload {...uploadProps}>
              <div style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center'
              }}>
                {imageUrl && (
                  <img
                    src={imageUrl}
                    alt="资讯配图"
                    style={{ width: '100%', maxHeight: '200px', marginBottom: '8px' }}
                  />
                )}
                <Button icon={<UploadOutlined />}>点击上传图片</Button>
              </div>
            </Upload>
          </Form.Item>

          <Form.Item
            name="newsItemContentBind"
            label="资讯详情"
            rules={[{ required: true, message: '请输入资讯详情' }]}
          >
            <RichTextEditor
              value={editorContent}
              onChange={(content, html) => {
                setEditorContent(content);
                form.setFieldsValue({ newsItemContentBind: html });
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default NewsPage;